package models

import (
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"go-admin/global/orm"
	"go-admin/tools"
	"strconv"
)

type VRBuild struct {
	ZxBuild
	OrderId    string `json:"orderId, omitempty"`
	CustomName string `json:"customName, omitempty"`
	CustomTel  string `json:"customTel, omitempty"`
	CustomAddr string `json:"customAddr, omitempty"`
}

// 获取VRBuild
func (e *VRBuild) GetBuildById(buildId string) (VRBuild, error) {
	var doc VRBuild
	if tools.NullStr(buildId) {
		return doc, errors.New("BuildId is empty")
	}
	selectSql := "SELECT zb.*, zo.custom_name, zo.custom_tel,zo.custom_addr" +
		" from zx_build zb" +
		" join zx_order zo on zb.id = zo.build_id AND zb.id = " + buildId

	orm.Eloquent.Raw(selectSql).Scan(&doc)
	return doc, nil
}

// 获取ZxDesign带分页
func (e *VRBuild) GetBuildPage(pageSize int, pageIndex int) ([]VRBuild, int, error) {
	var ret []VRBuild

	selectSql := "SELECT zb.*" +
		", zo.id as order_id, zo.custom_name, zo.custom_tel, zo.custom_addr"
	where := " from zx_build zb join zx_order zo on zb.id = zo.build_id" +
		" where zo.deleted_at IS NULL"
	if e.CustomName != "" {
		where = fmt.Sprintf("%s AND zo.custom_tel like '%%%s%%'", where, e.CustomName)
	}
	if e.CustomTel != "" {
		where = fmt.Sprintf("%s AND zo.custom_tel = %s", where, e.CustomTel)
	}
	if e.CustomAddr != "" {
		where = fmt.Sprintf("%s AND zo.custom_addr like '%%%s%%'", where, e.CustomAddr)
	}
	if e.BuilderId == 0 {
		where = fmt.Sprintf(" %s AND (zb.builder_id = %s OR zo.create_by = %s)", where, e.CreateBy, e.CreateBy)
	} else {
		where = fmt.Sprintf(" %s AND zb.builder_id = %d", where, e.BuilderId)
	}
	if e.BuildState != "" {
		where = fmt.Sprintf("%s AND zb.build_state = '%s'", where, e.BuildState)
	}
	var count int
	selectCountSql := "SELECT count(*) " + where
	orm.Eloquent.Raw(selectCountSql).Count(&count)
	pageSql := " LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((pageIndex-1)*pageSize)
	selectSql = selectSql + where + pageSql + ";"
	logrus.Info("sql:", selectSql)
	orm.Eloquent.Raw(selectSql).Scan(&ret)
	// 数据权限控制(如果不需要数据权限请将此处去掉)
	//dataPermission := new(DataPermission)
	//dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
	//table, err := dataPermission.GetDataScope(e.TableName(), table)
	//if err != nil {
	//	return nil, 0, err
	//}
	return ret, count, nil
}
